import { getRefreshToken } from "../http/user";
import { useMain, store } from "@/store/index";
import OSS from "ali-oss";
import router from "@/routes/index"
import { getFrontAccess, getSystemEnvironmentInfo } from "../http/device";
import { storeToRefs } from 'pinia';

const useMainStore = useMain(store);//pinia

// 刷新令牌
export function getUserRefreshToken() {
    return new Promise((resolve, reject) => {
        getRefreshToken().then((res: any) => {
            if (res && res.result) {
                useMainStore.updatedAuthToken(res.result.authToken);
                useMainStore.updatedRefreshToken(res.result.refreshToken);
                let { userInfo } = storeToRefs(useMainStore);
                if (userInfo.value) {
                    if (res.result.authToken && res.result.refreshToken && (userInfo.value.type == 0 || userInfo.value.type == 1 || userInfo.value.type == 3 || userInfo.value.type == 4)) {
                        var date = new Date();
                        // 将日期增加一天，得到明天的日期对象
                        date.setDate(date.getDate() + 1);
                        document.cookie = "authToken=" + res.result.authToken + "; domain=" + import.meta.env.VITE_TARGET_URL + "; expires=" + date.toUTCString() + "; path=/";
                        document.cookie = "refreshToken=" + res.result.refreshToken + ";domain=" + import.meta.env.VITE_TARGET_URL + "; expires=" + date.toUTCString() + "; path=/";
                    }
                }
                // callBack();
                resolve(res);
            }
        })
    })

}

//校验密码是否符合规则
export function CheckPassWord(password: string) {
    let str = password;
    // let reg = /^(?![A-z0-9]+$)(?=.[^%&',;=?$\x22])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,12}$/
    // let reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,12}$/
    let reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_])[^\u4e00-\u9fa5]{8,12}$/;
    if (reg.test(str)) {
        return true;
    } else {
        return false;
    }
}

//获取oss下载文件地址
export async function getFileUrl(fileUrl: string) {
    let url = "";
    await getFrontAccess().then((res: any) => {
        if (res && res.result) {
            // console.log('42res', res);
            let store = new OSS({
                region: 'oss-cn-shenzhen',
                endpoint: import.meta.env.VITE_OSS_ENDPOINT,
                accessKeyId: res.result.accessKeyId,
                accessKeySecret: res.result.accessKeySecret,
                cname: true,
                bucket: res.result.bucketName,
                secure: import.meta.env.VITE_ENV == 'production' ? true : false
            })
            // const url = store.signatureUrl('device_material/20230606095245_1665899497467228162.jpg', {
            url = store.signatureUrl(fileUrl, {
                expires: 3600,
                response: {
                    'content-disposition': 'inline'
                }
            });

        }
    })
    // console.log('62url',url);

    return url;
}
//查看材料详情
export async function viewFileDetail(fileUrl: string) {
    if (!fileUrl) {
        return;
    }
    if (fileUrl.indexOf('oss.omnicity.cn') > -1) {
        let urlArr = fileUrl.split('device_material/');
        let fileUrl_text = 'device_material/' + urlArr[urlArr.length - 1];
        let url = await getFileUrl(fileUrl_text);//获取oss临时授权链接
        // console.log('url', url);
        if (url) {
            let officeUrl;
            let strArr = fileUrl.split('.');
            let fileType = strArr[strArr.length - 1];
            if (fileType == 'doc' || fileType == 'docx' || fileType == 'xls' || fileType == 'xlsx') {//如果是word文档
                officeUrl = 'http://view.officeapps.live.com/op/view.aspx?src=' + encodeURIComponent(url);
            } else {
                officeUrl = url;
            }
            window.open(officeUrl, '_target')
        }
    } else {
        window.open(fileUrl, '_target')
    }


}

//查看文件详情
export async function getFileDetail(fileUrl: string, fileName: string) {
    if (!fileUrl) {
        return;
    }
    if (fileUrl.indexOf('oss.omnicity.cn') > -1) {
        let urlArr = fileUrl.split(fileName);
        let fileUrl_text = fileName + urlArr[urlArr.length - 1];
        let url = await getFileUrl(fileUrl_text);//获取oss临时授权链接
        // console.log('url',url);
        if (url) {
            let officeUrl;
            let strArr = fileUrl.split('.');
            let fileType = strArr[strArr.length - 1];
            if (fileType == 'doc' || fileType == 'docx' || fileType == 'xls' || fileType == 'xlsx') {//如果是word文档
                officeUrl = 'http://view.officeapps.live.com/op/view.aspx?src=' + encodeURIComponent(url);
            } else {
                officeUrl = url;
            }
            window.open(officeUrl, '_target')
        }
    } else {
        window.open(fileUrl, '_target')
    }


}

//判断是否在弹窗中的请求接口
export function isDialog(url: string | undefined) {
    let urlArr = ['/msg/msg/queryDetail', '/device/gatewayAlarm/getDetail', '/user/user/queryUserDetail', '/user/user/addUser', '/user/user/editUser', '/user/user/resetPwd', '/user/role/queryRoleDetail', '/user/role/addRole', 'user/dpt/addDpt', '/user/dpt/editDpt', 'msg/alarmRule/queryAlarmRuleDetail', 'msg/gatewayAlarm/getDetail', 'msg/alarmRecord/queryDetail', 'device/device/queryPlayUrl', 'device/space/add', 'device/space/getDetail', 'device/space/getQrCodeList', 'device/devicePoint/queryPoint', 'msg/noticePlatform/detail', 'msg/noticePlatform/add', 'device/useTypeFloor/getDetail', 'device/useTypeFloor/add', 'device/useTypeFloor/edit', 'device/useType/edit', 'device/useType/add', 'device/space/edit', 'device/useTypeRoom/getTreeDataByUseTypeId', 'device/useTypeRoom/getRoomsByFloorId', 'device/useTypeRoom/add', 'device/useTypeRoom/queryRoomSate', 'device/company/edit', 'device/company/add', 'device/company/getDetail', 'device/company/getTreeDataByUseTypeId', 'device/company/getTreeDataById', 'device/spaceStation/add', 'device/companyDept/getTreeData', 'device/companyDept/getUserListByDeptId', 'device/useTypeRoom/getRoomTreeData', 'device/company/getCompanyList', 'device/spaceStation/edit','/device/spaceTypeOwin/add','/device/spaceTypeOwin/edit'];
    let result = false;
    urlArr.forEach(item => {
        if (url && url.indexOf(item) > -1) {
            result = true;
        }
    })

    //如果是消息页面,设备报警查看详情时,返回false
    let messageType = useMainStore.messageType;
    if (url && url.indexOf('/msg/msg/queryDetail') > -1 && messageType == '2') {
        result = false;
    }

    return result;
}

//仅仅校验手机号，不校验座机号
export function validatePhone(phone: string) {
    let reg = /^[1]\d{10}$/;
    phone = String(phone);
    if (!phone.trim() || !reg.test(phone.trim())) {
        return false;
    }
    return true;
}


//判断按钮权限
export function isButtonDisabled(value: any) {
    const useMainStore = useMain(store);
    // console.log('window.location.pathname',window.location.pathname);

    // let currentPath = window.location.pathname;
    let currentPath = router.currentRoute.value.path;
    const menuListInfo = useMainStore.menuListInfo;
    let permissionBtn: any[] = [];
    menuListInfo.forEach((item: any) => {
        if (item.pageUrl == currentPath) {
            permissionBtn = item.children ? item.children : [];
        } else {
            if (item.children && item.children.length > 0) {
                item.children.forEach((item2: any) => {
                    if (item2.pageUrl == currentPath) {
                        permissionBtn = item2.children ? item2.children : [];
                    }
                })
            }
        }
    })
    if (value) {
        // 判断传递进来的按钮权限，用户是否拥有
        // Array.some() 数组中有一个结果是true返回true，剩下的元素不会再检测

        const hasPermission = permissionBtn.some((role: any) => {
            return value == role.pageUrl;
        });

        // 当用户有这个按钮权限时，返回false,否则返回true
        if (hasPermission) {
            return false;
        } else {
            return true;
        }
    }
}

//获取指定cookie
export function getCookie(name: string) {
    const cookies = document.cookie.split("; ");
    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].split("=");
        if (cookie[0] === name) {
            return cookie[1];
        }
    }
    return null;
};

//删除指定cookie
export function deleteCookie(name: string) {

    // const domain = '.test.com';
    const domain = import.meta.env.VITE_TARGET_URL;
    document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; domain=${domain}; path=/;`;
};

//计算表格每列的宽度
export function flexWidth(prop: string, tableData: Array<any>, title: string, num = 0) {
    if (!tableData || tableData.length === 0) {
        // 表格没数据不做处理
        return
    }
    let flexWidth = 0 // 初始化表格列宽
    let columnContent = '' // 占位最宽的内容
    let canvas = document.createElement('canvas')
    let context = canvas.getContext('2d')
    context!.font = '14px Microsoft YaHei'
    if (prop === '' && title) {
        // 标题长内容少的，取标题的值,
        columnContent = title
    } else {
        // 获取该列中占位最宽的内容
        let index = 0
        for (let i = 0; i < tableData.length; i++) {
            const now_temp = tableData[i][prop] + ''
            const max_temp = tableData[index][prop] + ''
            const now_temp_w = context!.measureText(now_temp).width
            const max_temp_w = context!.measureText(max_temp).width
            if (now_temp_w > max_temp_w) {
                index = i
            }
        }
        columnContent = tableData[index][prop]
        // 比较占位最宽的值跟标题、标题为空的留出四个位置
        const column_w = context!.measureText(columnContent).width
        const title_w = context!.measureText(title).width
        if (column_w < title_w) {
            columnContent = title || '占位符呀'
        }
    }
    // 计算最宽内容的列宽
    let width = context!.measureText(columnContent)
    flexWidth = width.width + 24 + num
    return flexWidth + 'px'
}

export function filterMenuData(data: any) {
    for (let i = 0; i < data.length; i++) {
        const item = data[i];

        if (item.children && item.children.length > 0) {
            // 如果当前项有子项，则递归处理子项
            filterMenuData(item.children);

            // 检查当前项的 children 中是否有满足条件的项
            const shouldDelete = item.children.every((child: any) => {
                return (child.type === 3 && child.pageUrl && !child.pageUrl.includes('_list'));
            });

            // 如果满足条件，则删除当前项
            if (shouldDelete) {
                data.splice(i, 1);
                i--; // 减少索引以补偿删除项
            }
        }
    }
}

//获取当前路由权限列表
export function getPermissionBtn() {
    const menuListInfo = useMainStore.menuListInfo;
    // console.log('useMainStore', menuListInfo);
    // console.log('window.location.pathname',window.location.pathname);

    // let currentPath = window.location.pathname;
    let currentPath = router.currentRoute.value.path;
    let permissionBtn: any[] = [];
    menuListInfo.forEach((item: any) => {
        if (item.pageUrl == currentPath) {
            permissionBtn = item.children ? item.children : [];
        } else {
            if (item.children && item.children.length > 0) {
                item.children.forEach((item2: any) => {
                    if (item2.pageUrl == currentPath) {
                        permissionBtn = item2.children ? item2.children : [];
                    }
                })
            }
        }
    })
    return permissionBtn;
}

//获取当前接口地址环境
export function getenv(callback:any) {
    return new Promise((resolve, reject) => {
        getSystemEnvironmentInfo().then((res: any) => {
            callback(res);
            resolve(res);
        })
    })

}

//获取当前接口地址环境
export function getenvInfo(currentEnv:string) {
    // let envInfo = currentEnv == 'sjs';
    let envInfo = false;
    if(currentEnv.indexOf('sjs')>-1){
        envInfo = true;
    }
    return envInfo;
}

//获取深交所mqtt地址
export function getMqttUrl() {
    let mqtt_url = "";
    if(import.meta.env.VITE_ENV!='production'){
        mqtt_url = import.meta.env.VITE_MQTT_URL;
    }else{
        mqtt_url = "ws://" + window.location.host + "/mqtt";
    }
    return mqtt_url;
}